package net.lijingye.education.service.impl;

import net.lijingye.education.dao.TokenDao;
import net.lijingye.education.dao.UserDao;
import net.lijingye.education.entity.Token;
import net.lijingye.education.entity.User;
import net.lijingye.education.exception.AlreadyLoginException;
import net.lijingye.education.exception.DaoException;
import net.lijingye.education.exception.ObjectNotExistsException;
import net.lijingye.education.exception.PasswordNotMatchException;
import net.lijingye.education.service.AuthService;
import net.lijingye.education.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created by LijingYe on 2016/4/3.
 */
@Service
@Transactional
public class AuthServiceImpl implements AuthService {
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private UserDao userDao;

    public Token doLogin(String userId, String userPassword) throws DaoException, ObjectNotExistsException, PasswordNotMatchException, AlreadyLoginException {
        User user = userDao.getById(userId);
        if (null == user) {
            throw new ObjectNotExistsException("User `" + userId + "`");
        }
        if (!user.getPassword().equals(userPassword)) {
            throw new PasswordNotMatchException("User `" + userId + "`");
        }
        Token token = tokenDao.getById(userId);
        if (null == token) {
            token = new Token(user.getId(), null);
        }
        String accessToken = MD5Util.MD5(user.getId() + String.valueOf((new Date()).getTime()));
        while (tokenDao.isAccessTokenAlreadyExists(accessToken)) {
            accessToken = MD5Util.MD5(user.getId() + String.valueOf((new Date()).getTime()));
        }
        token.setAccessToken(accessToken);
        tokenDao.saveOrUpdate(token);
        return token;
    }

    public void doLogout(String accessToken) throws DaoException {
        Token token = tokenDao.getByAccessToken(accessToken);
        tokenDao.delete(token);
    }

    public void changePassword(String accessToken, String password, String newPassword) throws DaoException, PasswordNotMatchException {
        Token token = tokenDao.getByAccessToken(accessToken);
        User user = userDao.getById(token.getId());
        if (!user.getPassword().equals(password)) {
            throw new PasswordNotMatchException("User `" + user.getId() + "`");
        }
        user.setPassword(newPassword);
        userDao.update(user);
        tokenDao.delete(token);
    }

    public boolean isAccessTokenValid(String accessToken) {
        try {
            return tokenDao.isAccessTokenAlreadyExists(accessToken);
        } catch (DaoException e) {
            e.printStackTrace();
            return false;
        }
    }
}
